import { BetaSchemaForm, DragSortTable, ProFormColumnsType } from "@ant-design/pro-components"
import { Button, Form, FormInstance, Popconfirm, message } from "antd";
import { useEffect, useState } from "react";
import { getSysByCode, getSysDictByType } from "../service";
import { PlusOutlined } from "@ant-design/icons";
import { useRequest } from "@umijs/max";

const getUiLocastions = async () => {
    const res = await getSysDictByType({
        category: "ui_location_type"
    })
    return res?.data?.ui_location_type?.map((item: any) => {
        return {
            label: item?.name,
            value: item?.value,
        }
    })
}

const useColumns = ({ record }: { record?: any }) => {
    const [extendForm, setExtendForm] = useState([])
 
    const { data: sysDictByTypeData } = useRequest(async () => {
        const res = await getSysDictByType({
            category: "mouse,keyboard,browser,wait,assertion"
        })
        const mapText = {
            mouse: '鼠标',
            keyboard: '键盘',
            browser: '浏览器',
            wait: '等待',
            assertion: '断言',
        }
        return {
            data: Object.keys(res?.data as any).map((key: any) => {
                return {
                    label: mapText[key],
                    value: key,
                    children: res?.data?.[key]?.map((item: any) => {
                        return {
                            ...item,
                            label: item?.name,
                            value: item?.value
                        }
                    })
                }
            })
        }
    }, {
        cacheKey: 'sysDictByTypeData',
        onSuccess(data) {
            const operationTypeList = record?.operationTypeList
            if (Array.isArray(operationTypeList)) {
                const find = data?.find(item => item?.value === operationTypeList?.[0])
                const target = find?.children?.find((item: any) => item?.value == operationTypeList?.[1])
                getExtendForm(target?.extend)
            }

        }
    })

    const getExtendForm = (extend: any) => {
        try {
            extend = JSON.parse(extend)
        } catch (e) {
            return
        }
        const newData = extend?.map((item: any) => {
            if (item.field === 'locationType') {
                return {
                    title: '元素定位类型',
                    dataIndex: item?.field,
                    valueType: 'select',
                    width: 240,
                    formItemProps: {
                        rules: [
                            {
                                required: true,
                                message: '此项为必填项',
                            },
                        ],
                    },
                    request() {
                        return getUiLocastions()
                    },
                }
            }

            return {
                title: item?.name,
                dataIndex: item?.field,
                formItemProps: {
                    rules: [
                        {
                            required: true,
                            message: '此项为必填项',
                        },
                    ],
                },
            }
        })
        setExtendForm(newData || [])
    }

    const onOperationTypeChange = (value: any, option: any) => {
        getExtendForm(option?.[1].extend)
    }

    const columns: ProFormColumnsType<any, "text">[] = [
        {
            title: '步骤名称',
            dataIndex: 'name',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            // width: 'xs',
        },
        {
            title: '操作类型',
            dataIndex: 'operationTypeList',
            valueType: 'cascader',
            formItemProps: {
                rules: [
                    {
                        required: true,
                        message: '此项为必填项',
                    },
                ],
            },
            width: 240,
            async request() {
                return sysDictByTypeData || []
            },
            fieldProps: {
                onChange: onOperationTypeChange
            }
        },
        ...extendForm,
        {
            title: '是否截图',
            dataIndex: 'isScreenshot',
            valueType: 'switch',
            initialValue: false,
            fieldProps: {
                checkedChildren: '是',
                unCheckedChildren: '否'
            }
        },
        {
            title: '失败是否继续',
            dataIndex: 'isContinue',
            valueType: 'switch',
            initialValue: false,
            fieldProps: {
                checkedChildren: '是',
                unCheckedChildren: '否'
            }
        },
    ]

    return {
        columns,
        extendForm,
        setExtendForm,
        sysDictByTypeData
    }
}

const EditRow = (props: any) => {
    const [editForm] = Form.useForm()
    const { columns } = useColumns({ record: props?.record })

    return <BetaSchemaForm<any>
        key={'edit'}
        layoutType="ModalForm"
        form={editForm}
        modalProps={{
            title: '编辑步骤',
            width: 600,
        }}
        columns={columns}
        trigger={<a key="config" onClick={async () => {
            editForm.setFieldsValue({
                ...props?.record,
                operationType: props?.record?.operationTypeList
            })
        }}>
            编辑
        </a>}
        // formRef={formRef}
        onFinish={async (values) => {
            console.log('values', props?.value, values);

            const steps = props?.value || []
            const newSteps = steps.map((item: any) => {
                if (item?.key == props?.record?.key) {
                    item = {
                        ...item,
                        ...values,
                    }
                }
                return item
            })
            props?.onChange?.([...newSteps])
            return true
        }}
    />
}

const CustomDragTable = (props: any) => {
    const [dataSource, setDataSource] = useState<any[]>([]);
    const { columns, setExtendForm, sysDictByTypeData } = useColumns({})
    const [addForm] = Form.useForm()
    
    const handleDragSortEnd = (
        beforeIndex: number,
        afterIndex: number,
        newDataSource: any,
    ) => {
        // console.log('排序后的数据', newDataSource);
        setDataSource(newDataSource);
        // message.success('修改列表排序成功');
        props?.onChange(newDataSource)
    };

    useEffect(() => {
        setDataSource(props?.value?.map((item: any) => ({ ...item, key: item.id || item.key })))
    }, [props?.value])

    return <>
        <BetaSchemaForm<any>
            layoutType="ModalForm"
            form={addForm}
            modalProps={{
                title: '新增步骤',
                width: 600,
            }}
            columns={columns}
            trigger={<Button onClick={() => {
                addForm.resetFields()
                setExtendForm([])
            }}
                icon={<PlusOutlined />}
                style={{ marginBottom: 15 }}>新增</Button>}
            // formRef={formRef}
            onFinish={async (values) => {
                const steps = dataSource || []
                steps.push({
                    ...values,
                    key: Date.now()
                })
                props?.onChange?.([...steps])
                return true
            }}
        />

        <DragSortTable
            scroll={{ x: 'max-content' }}
            columns={[
                {
                    title: '',
                    dataIndex: 'num',
                    fixed: 'left',
                    width: 40,
                },
                {
                    title: '序号',
                    valueType: 'indexBorder',
                    fixed: 'left',
                    width: 60
                },
                {
                    title: '步骤名称',
                    dataIndex: 'name',
                    fixed: 'left',
                    width: 150,
                },
                {
                    title: '步骤操作类型',
                    dataIndex: 'operationTypeList',
                    valueType: 'cascader',
                    async request() {
                        return sysDictByTypeData || []
                    },
                },
                {
                    title: 'UI元素定位类型',
                    dataIndex: 'locationType',
                    valueType: 'select',
                    request() {
                        return getUiLocastions()
                    },
                },
                {
                    title: 'UI元素定位表达式',
                    dataIndex: 'locationExpress'
                },
                {
                    title: '元素查找最长等待时间',
                    dataIndex: 'elementWait'
                },
                {
                    title: '步骤值',
                    dataIndex: 'value'
                },
                {
                    title: '预期属性',
                    dataIndex: 'expectKey'
                },
                {
                    title: '预期值',
                    dataIndex: 'expectValue'
                },
                {
                    title: '步骤描述',
                    dataIndex: 'description'
                },
                {
                    title: '断言失败是否继续执行',
                    dataIndex: 'isContinue',
                    valueType: 'switch',
                    fieldProps: {
                        checkedChildren: '是',
                        unCheckedChildren: '否'
                    }
                },
                {
                    title: '是否截图',
                    dataIndex: 'isScreenshot',
                    valueType: 'switch',
                    fieldProps: {
                        checkedChildren: '是',
                        unCheckedChildren: '否'
                    }
                },
                {
                    title: '目标UI元素定位类型',
                    dataIndex: 'targetLocationType'
                },
                {
                    title: '目标UI元素定位表达式',
                    dataIndex: 'targetLocationExpress'
                },
                {
                    title: '目标元素查找最长等待时间',
                    dataIndex: 'targetElementWait'
                },
                {
                    title: '创建时间',
                    dataIndex: 'gmtCreate',
                    valueType: 'dateTime',
                },
                {
                    title: '更新时间',
                    dataIndex: 'gmtModified',
                    valueType: 'dateTime',
                },
                {
                    title: '操作',
                    dataIndex: 'option',
                    valueType: 'option',
                    fixed: 'right',
                    render: (_, record: any, index) => [
                        <EditRow key='edit' record={record} onChange={props?.onChange} value={dataSource} />,
                        <Popconfirm key='del' title="是否要删除此行？" onConfirm={() => {
                            const steps = dataSource || []
                            const newSteps = steps?.filter((item: any) => item.key !== record?.key)
                            props?.onChange?.([...newSteps])
                        }}>
                            <a onClick={() => {
                            }}>删除</a>
                        </Popconfirm>

                    ],
                },
            ]}
            rowKey="key"
            toolBarRender={false}
            search={false}
            dataSource={dataSource}
            pagination={false}
            dragSortKey="num"
            onDragSortEnd={handleDragSortEnd}
        />
    </>
}

export default CustomDragTable